<template>
  <ContentWrap
    class="mb-0!"
    :class="[
      footer
        ? '!h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height)-10px)]'
        : '!h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-20px)]'
    ]"
    :bodyStyle="{ height: '100%', padding: '5px 0' }"
  >
    <div class="w-full !h-full flex flex-col justify-between">
      <el-scrollbar view-class="flex-auto p-x-20px p-y-10px">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="70px"
          v-loading="formLoading"
          hide-required-asterisk
          require-asterisk-position="right"
        >
          <div class="flex justify-center my-10px">
            <div class="flex pos-relative w-[120px]">
              <el-image
                v-if="formData.avatar"
                class="w-[120px] h-[120px] rounded-[4px] align-middle"
                :src="formData.avatar"
              />
              <el-image
                v-else
                class="w-[120px] h-[120px] rounded-[4px] align-middle"
                :src="formData.sex == 1 ? avatarNan : avatarNv"
              />
            </div>
          </div>
          <el-form-item label="会员姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入会员姓名" class="!w-100" />
          </el-form-item>
          <el-form-item label="会员昵称" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请输入会员昵称" class="!w-100" />
          </el-form-item>
          <el-form-item label="会员性别" prop="sex">
            <el-radio-group v-model="formData.sex">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :value="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入手机号码" class="!w-100" />
          </el-form-item>
          <el-form-item label="消费密码" prop="password" v-if="formData.id == undefined">
            <el-input
              v-model="formData.password"
              maxlength="6"
              show-password
              autocomplete="new-password"
              type="password"
              :formatter="formatterCode"
              placeholder="请输入6位纯数字密码"
              clearable
              class="!w-100"
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPassword" v-if="formData.id == undefined">
            <el-input
              v-model="formData.checkPassword"
              maxlength="6"
              show-password
              autocomplete="new-password"
              type="password"
              :formatter="formatterCode"
              placeholder="请输入6位纯数字密码"
              clearable
              class="!w-100"
            />
          </el-form-item>
          <el-form-item label="会员生日" prop="birthday">
            <!-- <el-date-picker
          v-model="formData.birthday"
          type="date"
          value-format="x"
          placeholder="选择出生日期"
          class="!w-100"
        /> -->
            <div class="flex w-100%">
              <el-date-picker
                v-model="formData.year"
                value-format="YYYY"
                type="year"
                placeholder="年"
                class="!w-100%"
              />

              <el-select v-model="formData.month" placeholder="月" class="ml-5px">
                <el-option key="1" label="1月" value="01" />
                <el-option key="2" label="2月" value="02" />
                <el-option key="3" label="3月" value="03" />
                <el-option key="4" label="4月" value="04" />
                <el-option key="5" label="5月" value="05" />
                <el-option key="6" label="6月" value="06" />
                <el-option key="7" label="7月" value="07" />
                <el-option key="8" label="8月" value="08" />
                <el-option key="9" label="9月" value="09" />
                <el-option key="10" label="10月" value="10" />
                <el-option key="11" label="11月" value="11" />
                <el-option key="12" label="12月" value="12" />
              </el-select>
              <el-select v-model="formData.day" placeholder="日" class="ml-5px">
                <el-option key="1" label="1日" value="01" />
                <el-option key="2" label="2日" value="02" />
                <el-option key="3" label="3日" value="03" />
                <el-option key="4" label="4日" value="04" />
                <el-option key="5" label="5日" value="05" />
                <el-option key="6" label="6日" value="06" />
                <el-option key="7" label="7日" value="07" />
                <el-option key="8" label="8日" value="08" />
                <el-option key="9" label="9日" value="09" />
                <el-option key="10" label="10日" value="10" />
                <el-option key="11" label="11日" value="11" />
                <el-option key="12" label="12日" value="12" />
                <el-option key="13" label="13日" value="13" />
                <el-option key="14" label="14日" value="14" />
                <el-option key="15" label="15日" value="15" />
                <el-option key="16" label="16日" value="16" />
                <el-option key="17" label="17日" value="17" />
                <el-option key="18" label="18日" value="18" />
                <el-option key="19" label="19日" value="19" />
                <el-option key="20" label="20日" value="20" />
                <el-option key="21" label="21日" value="21" />
                <el-option key="22" label="22日" value="22" />
                <el-option key="23" label="23日" value="23" />
                <el-option key="24" label="24日" value="24" />
                <el-option key="25" label="25日" value="25" />
                <el-option key="26" label="26日" value="26" />
                <el-option key="27" label="27日" value="27" />
                <el-option key="28" label="28日" value="28" />
                <el-option key="29" label="29日" value="29" />
                <el-option key="30" label="30日" value="30" />
                <el-option key="31" label="31日" value="31" />
              </el-select>
              <el-checkbox class="pl-5px" v-model="formData.isLunar"
                ><span class="font16">农历</span>
              </el-checkbox>
            </div>
          </el-form-item>
          <el-form-item label="会员身高" prop="height">
            <el-input-number
              v-model="formData.height"
              class="!w-100"
              :precision="2"
              :controls="false"
            >
              <template #suffix>
                <span>CM</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="当前体重" prop="weight">
            <el-input-number
              v-model="formData.weight"
              class="!w-100"
              :precision="2"
              :controls="false"
            >
              <template #suffix>
                <span>KG</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="目标体重" prop="targetWeight">
            <el-input-number
              v-model="formData.targetWeight"
              class="!w-100"
              :precision="2"
              :controls="false"
            >
              <template #suffix>
                <span>KG</span>
              </template>
            </el-input-number>
          </el-form-item>

          <el-form-item label="客户来源" prop="source">
            <el-select v-model="formData.source" class="!w-100">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CUSTOMER_SOURCE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="推荐人">
            <el-select
              v-model="formData.spreadId"
              class="!w-100"
              filterable
              placeholder="选择或搜索推荐人"
            >
              <el-option
                v-for="item in memberList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              >
                <span>{{ item.nickname }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="归属员工" prop="employeeId">
            <el-select
              v-model="formData.employeeId"
              placeholder="请选择归属员工"
              clearable
              class="!w-100"
            >
              <el-option
                v-for="item in employeeList"
                :key="item.employeeId"
                :label="item.employeeName"
                :value="item.employeeId"
              >
                <span>{{ item.employeeName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户标签" prop="tagIds">
            <MemberTagSelect v-model="formData.tagIds" show-add />
          </el-form-item>
          <el-form-item label="用户分组" prop="groupId">
            <MemberGroupSelect v-model="formData.groupId" :class-style="'w-100%!'" />
          </el-form-item>

          <el-form-item label="推广人">
            <el-switch v-model="formData.spreadEnable" />
          </el-form-item>
          <el-form-item label="会员备注" prop="mark">
            <el-input
              type="textarea"
              v-model="formData.mark"
              class="!w-100"
              placeholder="请输入会员备注"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <el-row :gutter="10" class="mt-10px w-full mx-0!">
        <el-col :span="12">
          <el-button
            @click="submitForm"
            type="primary"
            size="large"
            class="w-full custom-text-18 h-50px!"
          >
            确定
          </el-button>
        </el-col>
        <el-col :span="12">
          <el-button
            @click="reset"
            type="primary"
            size="large"
            plain
            class="w-full custom-text-18 h-50px!"
          >
            返回
          </el-button>
        </el-col>
      </el-row>
    </div>
  </ContentWrap>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as UserApi from '@/api/member/user'
import * as ShopUserApi from '@/api/shop/system/user/index'
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const footer = computed(() => appStore.getFooter)
import MemberTagSelect from '@/views/member/tag/components/MemberTagSelect.vue'
import MemberGroupSelect from '@/views/member/group/components/MemberGroupSelect.vue'
import { verifiyDigitalCode } from '@/utils/formatter'
import avatarNan from '@/assets/imgs/avatar_nan.png'
import avatarNv from '@/assets/imgs/avatar_nv.png'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  mobile: undefined,
  password: undefined,
  status: 1,
  nickname: undefined,
  avatar: undefined,
  name: undefined,
  sex: 2,
  areaId: undefined,
  birthday: undefined,
  mark: undefined,
  tagIds: [],
  groupId: undefined,
  weight: undefined,
  targetWeight: undefined,
  height: undefined,
  isLunar: false,
  employee: undefined,
  employeeId: undefined,
  year: undefined,
  month: undefined,
  day: undefined,
  source: undefined,
  spreadId: undefined,
  spreadName: undefined,
  spreadEnable: false,
  checkPassword: undefined
})

/** 重置按钮操作 */
const reset = () => {
  resetForm()
  emit('back')
}
const equalToPassword = (rule, value, callback) => {
  if (formData.value.password !== value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const formRules = reactive({
  mobile: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: t('profile.rules.truephone'),
      trigger: 'blur'
    }
  ],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  checkPassword: [
    { required: true, trigger: 'blur', message: '请再次输入您的密码' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
})
const formRef = ref() // 表单 Ref
const formatterCode = (value: string) => {
  return verifiyDigitalCode(value)
}
const employeeList = ref<any>([]) //员工列表
const memberList = ref<any>([]) //会员列表
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(id)
    } finally {
      formLoading.value = false
    }
  }

  employeeList.value = await ShopUserApi.getEmployeeList()
  const memberData = await UserApi.getUserPage({})
  memberList.value = memberData.list
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success', 'back']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as any
    if (data.spreadId) {
      data.spreadName = memberList.value.find((item) => {
        return item.id == data.spreadId
      }).nickname
    }
    if (data.employeeId) {
      data.employee = employeeList.value.find((item) => {
        return item.employeeId == data.employeeId
      }).employeeName
    }

    if (formType.value === 'create') {
      // 说明：目前暂时没有新增操作。如果自己业务需要，可以进行扩展
      await UserApi.createUser(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserApi.updateUser(data)
      message.success(t('common.updateSuccess'))
    }
    reset()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    mobile: undefined,
    password: undefined,
    status: 1,
    nickname: undefined,
    avatar: undefined,
    name: undefined,
    targetWeight: undefined,
    sex: 1,
    areaId: undefined,
    birthday: undefined,
    mark: undefined,
    tagIds: [],
    groupId: undefined,
    weight: undefined,
    height: undefined,
    isLunar: false,
    employee: undefined,
    employeeId: undefined,
    year: undefined,
    month: undefined,
    day: undefined,
    source: undefined,
    spreadId: undefined,
    spreadName: undefined,
    spreadEnable: false,
    checkPassword: undefined
  }
  formRef.value?.resetFields()
}
</script>
